package cn.ticsmyc.tools.multiThread.masterSlave;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Future;

/**
 * @author Ticsmyc
 * @date 2021-06-04 11:26
 */
public class RoundRobinSubTaskDispatcherStrategy<T, V> implements SubTaskDispatchStrategy<T, V> {

    final List<Future<T>> subResult = new LinkedList<>();

    @Override
    public Iterator<Future<T>> dispatch(Set<? extends SlaveSpec<T, V>> slaves, TaskDivideStrategy<V> taskDivideStrategy) throws InterruptedException, SubTaskFailureException {
        V subTask;
        Object[] slave = slaves.toArray();
        int index = -1;
        while ((subTask = taskDivideStrategy.nextChunk()) != null) {
            int curIndex = (++index) % slave.length;
            Future<T> submit = ((SlaveSpec<T, V>) slave[curIndex]).submit(subTask);
            subResult.add(submit);
        }
        return subResult.iterator();
    }
}
